<?php
/**
 * Created by PhpStorm.
 * User: nightkid
 * Date: 2020/3/10
 * Time: 3:38 PM
 */

namespace App\Services;


use App\Model\QiniucallbackModel;
use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Config;

class QiniuService
{
    use Singleton;

    private static $model;

    function __construct()
    {
        if (!isset(self::$model)) {
            self::$model =new QiniucallbackModel();
        }
        return self::$model;

    }

    /**
     * 七牛callback
     * @param $params
     * @param $authorization
     * @return array
     */
    public function qiniuCallBack($params, $authorization)
    {
        $hash = $params['hash'] ?? '';
        $name = $params['name'] ?? '';
        $size = $params['size'] ?? '';
        $bucket = $params['bucket'] ?? '';
        $mime = $params['mime'] ?? '';
        $s1 = "";
        $app_id = $params['app_id'] ?? '';
        $user_id = $params['user_id'] ?? '';

        $authorization = isset($authorization[0])?$authorization[0]:'';
          if ($authorization) {
            $s1 = $this->strLeftPos($this->strRightPos($authorization, " "), ":");
        }

        if ($s1 == Config::getInstance()->getConf('QINIU.QINIU_ACCESS_KEY')) {
            $this->qiniuSaveLog($hash, $name, $size, $mime, $bucket,$app_id,$user_id);
            $data = [
                "success" => true,
                "hash" => $hash,
                "name" => $name,
                "size" => $size,
                "bucket" => $bucket,
                "mime" => $mime,
                'addtime'=>date("Y-m-d H:i:s")
            ];
            return $data;
        } else {
            return false;
        }

    }


    function strLeftPos($str, $l)
    {
        $re = mb_strpos($str, $l);
        if ($re === false) {
            return $str;
        } else {
            return mb_substr($str, 0, $re);
        }
    }

    function strRightPos($str, $l)
    {
        $re = mb_strpos($str, $l);
        if ($re === false) {
            return "";
        } else {
            return mb_substr($str, $re + mb_strlen($l), mb_strlen($str) - $re - mb_strlen($l));
        }
    }

    /**
     * 保存七牛日志
     * @param $hash
     * @param $name
     * @param $size
     * @param $bucket
     * @param $mime
     * @return array|bool|mixed
     */
    public function qiniuSaveLog($hash, $name, $size, $mime, $bucket,$app_id,$user_id)
    {
        $res = QiniucallbackModel::create()->get(["hash" => $hash]);
        if ($res) {
            return true;
        }

        $data = [
            "hash" => $hash,
            "filename" => $name,
            "filesize" => $size,
            "mimetype" => $mime,
            "bucket" => $bucket,
            "status" => 1,
            'app_id'=>$app_id,
            'user_id'=>$user_id,
            'addtime'=>date("Y-m-d H:i:s")
        ];
      
       return QiniucallbackModel::create($data)->save();
    }
}